package com.yt.server.action;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.yt.server.api.IConnection;
import com.yt.server.api.IScope;
import com.yt.server.api.action.IActionCall;
import com.yt.server.api.action.IActionCallback;
import com.yt.server.api.action.IActionProxy;
import com.yt.server.messaging.Packet;

/**
 * 控制代理
 * 
 * @author 刘晶
 */
public class ActionProxy implements IActionProxy {

	private boolean specified = false;

	/**
	 * 代理的目标
	 */
	private IConnection connection = null;

	/**
	 * 当前接受的包
	 */
	private final ConcurrentMap<String, IActionCall> calls = new ConcurrentHashMap<String, IActionCall>();// <包Id,C>

	public ActionProxy() {
	}

	public ActionProxy(IConnection conn) {
		this.connection = conn;
	}

	public IActionCall getActionCall(String id) {
		return calls.get(id);
	}

	@Override
	public String getActionName(String id) {
		return getActionCall(id).getActionName();
	}

	@Override
	public IScope getActionScope(String id) {
		return getActionCall(id).getScope();
	}

	@Override
	public String getNamespace(String id) {
		return null;
	}

	@Override
	public String getMethod(String id) {
		return getActionCall(id).getActionMethodName();
	}

	@Override
	public boolean isMethodSpecified() {
		return specified;
	}

	/**
	 * @param packet
	 * @param callback
	 *            (callback必须要做的事件)
	 */
	@Override
	public IActionCall handlePacket(Packet packet, IActionCallback callback) {
		IActionCall call = handlePacket(packet);
		if (null != callback)
			call.registerCallback(callback);
		return call;
	}

	@Override
	public IActionCall handlePacket(Packet packet) {
		if (packet.getState() == IActionCall.STATUS_PENDING) {// 是否未处理
			// if (null == calls.get(call.getId()))
			// calls.putIfAbsent(call.getId(), call);
			return new ActionCall(packet, connection.getScope());
		}
		return null;
	}

	@Override
	public Packet handleActionCall(IActionCall call) {
		return (Packet) call.getResultPacket();
		// if (null == calls.get(call.getId())) {
		// calls.remove(call.getId());
		// }
		// return null;
	}

	/**
	 * 创建数据包
	 */
	@Override
	public Packet createPacket(Object object) {
		return new Packet(object);
	}

	/**
	 * 创建行为
	 */
	@Override
	public IActionCall createCall(Object object) {
		return null;
	}
}